#!/usr/bin/env python
# -*- coding:utf-8 -*- 

from flask_restful import Resource, reqparse
from flask import jsonify, request

from controller.sysAdminController import SysAdminController
from utils import commons
from utils.response_code import RET, error_map_EN
import json
from service.sysAdminService import SysAdminService


class SysAdminResource(Resource):

    # get
    @classmethod
    def get(cls, user_id=None):
        if user_id:
            kwargs = {
                'user_id': user_id
            }

            res = SysAdminController.get(**kwargs)
            if res['code'] == RET.OK:
                return jsonify(code=res['code'], message=res['message'], data=res['data'])
            else:
                return jsonify(code=res['code'], message=res['message'], data=res['data'])

        parser = reqparse.RequestParser()
        parser.add_argument('auto_id', location='args', required=False, help='auto_id参数类型不正确或缺失')
        parser.add_argument('user_id', location='args', required=False, help='user_id参数类型不正确或缺失')
        parser.add_argument('account', location='args', required=False, help='account参数类型不正确或缺失')
        parser.add_argument('password', location='args', required=False, help='password参数类型不正确或缺失')
        parser.add_argument('name', location='args', required=False, help='name参数类型不正确或缺失')
        parser.add_argument('mobile', location='args', required=False, help='mobile参数类型不正确或缺失')
        parser.add_argument('email', location='args', required=False, help='email参数类型不正确或缺失')
        parser.add_argument('gender', location='args', required=False, help='gender参数类型不正确或缺失')
        parser.add_argument('is_delete', location='args', required=False, help='is_delete参数类型不正确或缺失')
        parser.add_argument('create_time', location='args', required=False, help='create_time参数类型不正确或缺失')
        parser.add_argument('update_time', location='args', required=False, help='update_time参数类型不正确或缺失')
        
        parser.add_argument('Page', location='args', required=False, help='Page参数类型不正确或缺失')
        parser.add_argument('Size', location='args', required=False, help='Size参数类型不正确或缺失')

        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)

        res = SysAdminController.get(**kwargs)
        if res['code'] == RET.OK:
            return jsonify(code=res['code'], message=res['message'], data=res['data'], totalPage=res['totalPage'], totalCount=res['totalCount'])
        else:
            return jsonify(code=res['code'], message=res['message'], data=res['data']) 

    
    # delete
    @classmethod
    def delete(cls, user_id=None):
        if user_id:
            kwargs = {
                'user_id': user_id
            }

        else:
            return jsonify(code=RET.PARAMERR, message=error_map_EN[RET.PARAMERR], data='id不能为空')

        res = SysAdminController.delete(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])

    
    # put
    @classmethod
    def put(cls, user_id):
        if not user_id:
            return jsonify(code=RET.NODATA, message='primary key missed', error='primary key missed')

        parser = reqparse.RequestParser()
        parser.add_argument('account', location='json', required=False, help='account参数类型不正确或缺失')
        parser.add_argument('password', location='json', required=False, help='password参数类型不正确或缺失')
        parser.add_argument('name', location='json', required=False, help='name参数类型不正确或缺失')
        parser.add_argument('mobile', location='json', required=False, help='mobile参数类型不正确或缺失')
        parser.add_argument('email', location='json', required=False, help='email参数类型不正确或缺失')
        parser.add_argument('create_time', location='json', required=False, help='create_time参数类型不正确或缺失')
        parser.add_argument('update_time', location='json', required=False, help='update_time参数类型不正确或缺失')
        
        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)
        kwargs['user_id'] = user_id

        res = SysAdminController.update(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])

    
    # add
    @classmethod
    def post(cls):
        '''
        处理两种请求：
        1. /sysAdmin/login - 登录
        2. /sysAdmin - 添加管理员
        '''
        try:
            # 获取请求路径
            if request.path.endswith('/login'):
                # 登录处理
                parser = reqparse.RequestParser()
                parser.add_argument('account', type=str, required=True, 
                                  help='account参数不能为空')
                parser.add_argument('password', type=str, required=True, 
                                  help='password参数不能为空')
                args = parser.parse_args()
                result = SysAdminService.login(**args)
                return jsonify(result)
            
            else:
                # 原有的添加管理员处理
                parser = reqparse.RequestParser()
                parser.add_argument('SysAdminList', type=str, location='json', 
                                  required=False, help='SysAdminList参数类型不正确或缺失')

                kwargs = parser.parse_args()
                kwargs = commons.put_remove_none(**kwargs)

                if kwargs.get('SysAdminList'):
                    kwargs['SysAdminList'] = json.loads(kwargs['SysAdminList'])
                    for data in kwargs['SysAdminList']:
                        for key in ['is_delete']:
                            data.pop(key, None)
                    res = SysAdminController.add_list(**kwargs)

                else:
                    parser.add_argument('account', location='json', required=True, 
                                      help='account参数类型不正确或缺失')
                    parser.add_argument('password', location='json', required=True, 
                                      help='password参数类型不正确或缺失')
                    parser.add_argument('name', location='json', required=True, 
                                      help='name参数类型不正确或缺失')
                    parser.add_argument('mobile', location='json', required=True, 
                                      help='mobile参数类型不正确或缺失')
                    parser.add_argument('email', location='json', required=False, 
                                      help='email参数类型不正确或缺失')
                    parser.add_argument('gender', location='json', required=False,
                                        help='gender参数类型不正确或缺失')
                    parser.add_argument('create_time', location='json', required=False, 
                                      help='create_time参数类型不正确或缺失')
                    parser.add_argument('update_time', location='json', required=False, 
                                      help='update_time参数类型不正确或缺失')
                    
                    kwargs = parser.parse_args()
                    kwargs = commons.put_remove_none(**kwargs)

                    res = SysAdminController.add(**kwargs)

                return jsonify(code=res['code'], message=res['message'], data=res['data'])
                
        except Exception as e:
            print(f"Error: {str(e)}")  # 实际应该使用logger
            return jsonify({
                "code": "5000",
                "message": "服务器内部错误",
                "error": str(e)
            })
